package com.uaroadshow.tencent.web.controller.auth.weapp;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.uaroadshow.entity.user.UserSource;
import com.uaroadshow.entity.user.WechatAccount;
import com.uaroadshow.tencent.entity.weappauth.WeappAuth;
import com.uaroadshow.tencent.handle.WeappAuthHandler;
import com.uaroadshow.tencent.service.WeappAuthService;

/**
 * 
 * @author wangliwang
 *        
 */
@RestController
@RequestMapping("/weapp/auth")
public class WeappAuthRestController {
    
    @Autowired
    private WeappAuthHandler weappAuthHandler;
    
    @Autowired
    private WeappAuthService weappAuthService;
    
    /**
     * get openid by js_code
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/prepare", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult openid(@RequestParam("code") String code) {
        
        HttpResult httpResult = new HttpResult();
        
        Map<String, Object> result = weappAuthHandler.authenticate(code);
        
        return httpResult.success().data(result);
        
    }
    
    /**
     * 
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public HttpResult login(@RequestParam("session-key") String sessionKey, @RequestParam("encrypted-data") String encryptedData, @RequestParam("iv") String iv) {
        
        HttpResult httpResult = new HttpResult();
        
        // 1. get decrypt data
        WeappAuth weappAuth = weappAuthHandler.decrypt(encryptedData, sessionKey, iv);
        
        // 2. save wechat account
        WechatAccount account = weappAuthService.authorize(sessionKey, weappAuth, UserSource.uaroadshow_WEAPP_ACCOUNT);
        
        return httpResult.success().data("account", account).message("保存小程序微信授权信息成功");
        
    }
    
}
